package com.frejoys.common.util;

import cn.hutool.core.util.StrUtil;
import com.frejoys.common.config.ValueConfig;
import com.frejoys.common.service.AliStorageService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class AppConfigUtil {

    private final ValueConfig valueConfig;

    private final AliStorageService aliStorageService;

    private static AppConfigUtil appConfigUtil;

    @PostConstruct
    private void init() {
        appConfigUtil = this;
    }

    /**
     * 获取单个文件完整路径
     * @param fileName
     * @return
     */
    public static String getUrlPrefix(String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return "";
        }

        String[] arr = fileName.split(",");

        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i].startsWith("https") || arr[i].startsWith("http") ? arr[i] : appConfigUtil.aliStorageService.fileSignature(arr[i], getFileSize(null));
        }

        return StrUtil.join(",", arr);
    }

    /**
     * 获取单个文件完整路径
     * @param fileName
     * @param fileSize
     * @return
     */
    public static String getUrlPrefix(String fileName, String fileSize) {
        if (StrUtil.isEmpty(fileName)) {
            return "";
        }

        String[] arr = fileName.split(",");

        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i].startsWith("https") || arr[i].startsWith("http") ? arr[i] : appConfigUtil.aliStorageService.fileSignature(arr[i], getFileSize(fileSize));
        }

        return StrUtil.join(",", arr);
    }

    /**
     * 缩放文件
     * @return
     */
    public static String getFileSize(String fileSize) {
        String size = StrUtil.isNotEmpty(fileSize) ? fileSize : RequestUtil.fileSize();

        if (StrUtil.isNotEmpty(size)) {
            try {
                Integer intSize = Integer.valueOf(size);
                if (intSize > 0 && intSize < 1201) {
                    return "image/resize,m_lfit,w_" + intSize;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "image/resize,m_lfit,w_500";
    }

    /**
     * 删除文件url静态域名前缀
     * @param fileName
     * @return
     */
    public static String removeUrlPrefix(String fileName) {
        return StrUtil.removePrefix(fileName, appConfigUtil.valueConfig.getAliOssBucketUploadUrl());
    }


}
